using Duckov.Utilities;
using HarmonyLib;
using ItemStatsSystem.Items;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;

namespace AllGunsSixSlots
{
    [HarmonyPatch(typeof(ItemSetting_Gun), "Start")]
    public class AllGunsSettingPatch
    {
        static void Postfix(ItemSetting_Gun __instance)
        {
            // 启动协程进行异步处理
            __instance.StartCoroutine(HandleAllGunsAsync(__instance));
        }
        
        // 异步处理所有枪械
        private static IEnumerator HandleAllGunsAsync(ItemSetting_Gun gunSetting)
        {
            // 等待一帧，确保Item和其他组件完全初始化
            yield return null;
            
            var item = gunSetting.Item;
            if (item == null) 
            {
                UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] 枪械Item为null，跳过处理");
                yield break;
            }

            string gunName = item.DisplayName ?? "未知枪械";
            int typeID = item.TypeID;
            
            UnityEngine.Debug.Log($"[AllGunsSixSlots] 开始异步处理枪械: {gunName} (TypeID: {typeID})");
            
            // 等待资源加载和系统准备
            yield return WaitForSystemsReady();
            
            // 修改插槽配置
            yield return ModifyAllGunsSlotsAsync(item, gunName);
            
            UnityEngine.Debug.Log($"[AllGunsSixSlots] 完成异步处理枪械: {gunName}");
        }
        
        // ==================== 异步等待系统就绪 ====================
        private static IEnumerator WaitForSystemsReady()
        {
            // 等待Tag系统加载完成
            int maxWaitFrames = 10;
            int currentFrame = 0;
            
            while (currentFrame < maxWaitFrames)
            {
                var allTags = Resources.FindObjectsOfTypeAll<Tag>();
                if (allTags != null && allTags.Length > 0)
                {
                    // Tag系统已加载
                    break;
                }
                
                currentFrame++;
                yield return null; // 等待下一帧
            }
            
            if (currentFrame >= maxWaitFrames)
            {
                UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] Tag系统加载超时，可能影响插槽配置");
            }
        }
        
        // ==================== 异步插槽修改核心逻辑 ====================
        /// <summary>
        /// 为所有枪械修改插槽配置：统一设置为6个标准插槽
        /// 标准插槽：Scope、Muzzle、Grip、Stock、Tec、Mag
        /// </summary>
        internal static IEnumerator ModifyAllGunsSlotsAsync(ItemStatsSystem.Item item, string gunName = "枪械")
        {
            if (item.Slots == null)
            {
                UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] {gunName} 插槽集合为null，无法修改");
                yield break;
            }
            
            int currentSlotCount = item.Slots.Count;
            
            // 如果已经是6个插槽，跳过
            if (currentSlotCount == 6)
            {
                UnityEngine.Debug.Log($"[AllGunsSixSlots] {gunName} 已有6个插槽，跳过修改");
                yield break;
            }
            
            UnityEngine.Debug.Log($"[AllGunsSixSlots] 开始异步修改 {gunName} 插槽: {currentSlotCount} → 6");
            
            // 分步骤创建插槽，避免单帧性能峰值
            yield return CreateAndAddSlotsAsync(item, gunName);
            
            UnityEngine.Debug.Log($"[AllGunsSixSlots] 已完成异步修改 {gunName} 插槽，当前插槽数: {item.Slots.Count}");
        }
        
        /// <summary>
        /// 异步创建并添加缺失的插槽
        /// </summary>
        private static IEnumerator CreateAndAddSlotsAsync(ItemStatsSystem.Item item, string gunName)
        {
            // 定义标准插槽配置和顺序
            var standardSlots = new[]
            {
                ("Scope", AllGunsConfig.SlotTags.ScopeRequireTags, AllGunsConfig.SlotTags.ScopeExcludeTags),
                ("Muzzle", AllGunsConfig.SlotTags.MuzzleRequireTags, AllGunsConfig.SlotTags.MuzzleExcludeTags),
                ("Grip", AllGunsConfig.SlotTags.GripRequireTags, AllGunsConfig.SlotTags.GripExcludeTags),
                ("Stock", AllGunsConfig.SlotTags.StockRequireTags, AllGunsConfig.SlotTags.StockExcludeTags),
                ("Tec", AllGunsConfig.SlotTags.TecRequireTags, AllGunsConfig.SlotTags.TecExcludeTags),
                ("Magazine", AllGunsConfig.SlotTags.MagRequireTags, AllGunsConfig.SlotTags.MagExcludeTags)
            };
            
            int idx = 0;
            int addedSlotsCount = 0;
            
            List<ItemStatsSystem.Items.Slot> newSlots = new List<ItemStatsSystem.Items.Slot>();
            
            foreach (var slotConfig in standardSlots)
            {
                string slotKey = slotConfig.Item1;
                string[] requireTags = slotConfig.Item2;
                string[] excludeTags = slotConfig.Item3;
                
                // 检查是否已存在对应类型的插槽
                bool slotExists = false;
                
                // 遍历现有插槽，检查是否有相同类型的插槽
                foreach (var existingSlot in item.Slots.list)
                {
                    if (existingSlot == null) continue;
                    
                    // 检查插槽是否包含所需标签（简化匹配逻辑）
                    bool matchesRequiredTags = true;
                    if (requireTags != null && requireTags.Length > 0)
                    {
                        foreach (var tagName in requireTags)
                        {
                            var tag = FindTagByName(tagName);
                            if (tag != null && !existingSlot.requireTags.Contains(tag))
                            {
                                matchesRequiredTags = false;
                                break;
                            }
                        }
                    }
                    
                    if (matchesRequiredTags)
                    {
                        slotExists = true;
                        UnityEngine.Debug.Log($"[AllGunsSixSlots] {gunName} 已存在 {slotKey} 类型插槽: {existingSlot.Key}");
                        break;
                    }
                }
                
                // 如果不存在该类型插槽，则创建并插入
                if (!slotExists)
                {
                    var newSlot = CreateSlotWithTags(slotKey, requireTags, excludeTags);
                    if (newSlot != null)
                    {
                        // 在正确位置插入新插槽
                        if (idx < item.Slots.list.Count)
                        {
                            item.Slots.list.Insert(idx, newSlot);
                        }
                        else
                        {
                            item.Slots.list.Add(newSlot);
                        }
                        
                        newSlots.Add(newSlot);
                        addedSlotsCount++;
                        
                        UnityEngine.Debug.Log($"[AllGunsSixSlots] 已为 {gunName} 添加缺失插槽: {slotKey} (位置: {idx})");
                    }
                }
                
                idx++;
                
                // 每添加一个插槽等待一帧，避免性能峰值
                if (!slotExists)
                {
                    yield return null;
                }
            }
            
            foreach (var newSlot in newSlots) {
                newSlot.Initialize(item.Slots);
            }
            
            UnityEngine.Debug.Log($"[AllGunsSixSlots] 为 {gunName} 添加了 {addedSlotsCount} 个缺失插槽，总插槽数: {item.Slots.Count}");
            
            // 确保所有插槽都初始化完成
            yield return null;
        }
        
        /// <summary>
        /// 创建带有Tag配置的插槽
        /// </summary>
        private static ItemStatsSystem.Items.Slot CreateSlotWithTags(string slotKey, string[] requireTagNames, string[] excludeTagNames)
        {
            try
            {
                // 创建基础插槽
                var slot = new ItemStatsSystem.Items.Slot(slotKey);
                
                // 设置requireTags
                if (requireTagNames != null && requireTagNames.Length > 0)
                {
                    foreach (var tagName in requireTagNames)
                    {
                        var tag = FindTagByName(tagName);
                        if (tag != null)
                        {
                            slot.requireTags.Add(tag);
                        }
                        else
                        {
                            UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] 警告：找不到requireTag '{tagName}'，插槽{slotKey}可能无法正常工作");
                        }
                    }
                }
                
                // 设置excludeTags
                if (excludeTagNames != null && excludeTagNames.Length > 0)
                {
                    foreach (var tagName in excludeTagNames)
                    {
                        var tag = FindTagByName(tagName);
                        if (tag != null)
                        {
                            slot.excludeTags.Add(tag);
                        }
                        else
                        {
                            UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] 警告：找不到excludeTag '{tagName}'，插槽{slotKey}可能无法正常工作");
                        }
                    }
                }
                
                return slot;
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError($"[AllGunsSixSlots] 创建插槽{slotKey}时出错: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 通过名称查找Tag对象
        /// </summary>
        private static Tag FindTagByName(string tagName)
        {
            try
            {
                var allTags = Resources.FindObjectsOfTypeAll<Tag>();
                foreach (var loadedTag in allTags)
                {
                    if (loadedTag.name == tagName)
                    {
                        return loadedTag;
                    }
                }
                
                UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] 无法找到Tag: {tagName}");
                return null;
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError($"[AllGunsSixSlots] 查找Tag {tagName} 时出错: {ex.Message}");
                return null;
            }
        }
        
        // 调试方法保持不变
        private static void DebugSlots(ItemStatsSystem.Item item, string gunName)
        {
            if (item.Slots == null)
            {
                UnityEngine.Debug.Log($"[AllGunsSixSlots Debug] {gunName}没有插槽集合");
                return;
            }
            
            int slotCount = item.Slots.Count;
            UnityEngine.Debug.Log($"[AllGunsSixSlots Debug] {gunName}插槽信息: 共{slotCount}个插槽");
            
            for (int i = 0; i < slotCount; i++)
            {
                var slot = item.Slots.GetSlotByIndex(i);
                if (slot == null)
                {
                    UnityEngine.Debug.Log($"[AllGunsSixSlots Debug]   插槽{i}: null");
                    continue;
                }
                
                string requireTagsStr = slot.requireTags != null ? string.Join(", ", slot.requireTags) : "无";
                string excludeTagsStr = slot.excludeTags != null ? string.Join(", ", slot.excludeTags) : "无";
                
                UnityEngine.Debug.Log($"[AllGunsSixSlots Debug] 插槽{i}: key={slot.Key}, requireTags=[{requireTagsStr}], excludeTags=[{excludeTagsStr}]");
            }
        }
        
        // 在 AllGunsSettingPatch 类中添加这个重载方法以支持异步调用
        internal static IEnumerator ModifyAllGunsSlotsAsync(ItemStatsSystem.Item item, ItemSetting_Gun gunSetting = null, string gunName = "枪械")
        {
            // 如果没提供gunName，尝试从item获取
            if (gunName == "枪械" && item != null)
            {
                gunName = item.DisplayName ?? "未知枪械";
            }
            
            return ModifyAllGunsSlotsAsync(item, gunName);
        }
    }
}